/* types */
import { ConnectorSaveOptionsParams } from '@src/modules/connector/types';
/* model */
import { ConnectorBizTypeEnum, ConnectorBizTypeIdEnum, ConnectorDialogDetailData, ConnectorFieldEnNameEnum, ConnectorFieldTypeEnum } from '@src/modules/connector/model';
/* util */
import { isFalsy, isNotEmpty, isArray } from '@src/util/type';
import { message } from '@src/util/message';
import { t } from '@src/locales';

function connectorSaveValidate(detailValue: ConnectorDialogDetailData) {
  
  const toBizType = detailValue?.paasApp?.type
  const toBizTypeId = detailValue?.paasApp?.id
  
  // to 连接器表单是否为 客户表单
  const isToCustomer = toBizType == ConnectorBizTypeEnum.Customer && toBizTypeId == ConnectorBizTypeIdEnum.Customer
  // to 连接器表单是否非 客户表单
  const isToNotCustomer = isFalsy(isToCustomer)
  
  // to 连接器表单是否非 客户表单
  if (isToNotCustomer) {
    
    // 新建规则
    const insertRuleForms = detailValue?.insertRuleForms || []
    
    // 需要选择客户字段才可以的字段
    const needRelationCustomerFieldEnNames: string[] = [
      ConnectorFieldEnNameEnum.Linkman,
      ConnectorFieldEnNameEnum.CustomerAddress,
    ]
    
    // 需要选择客户字段才可以的字段
    const needRelationCustomerFieldEnTypes: string[] = [
      ConnectorFieldTypeEnum.Linkman,
      ConnectorFieldTypeEnum.CustomerAddress,
    ]
    
    // 是否有关联客户才可以使用的字段
    const isNeedRelationCustomerField = insertRuleForms.some(item => {
      
      const toEnName = item.field?.fieldName || ''
      const toFormType = item.field?.formType || ''
      
      const isHaveNeedRelationCustomerField = (
        needRelationCustomerFieldEnNames.includes(toEnName)
        || needRelationCustomerFieldEnTypes.includes(toFormType)
      )
      
      const isHaveValue = (
        item.rightFieldValue
        || (
          isNotEmpty(item.value) && isArray(item.value) && item.value?.every(Boolean)
        )
      )

      return isHaveNeedRelationCustomerField && isHaveValue
    })
    
    if (isNeedRelationCustomerField) {
      
      // 是否有客户字段
      const customerField = insertRuleForms.find(item => {
        
        const toEnName = item.field?.fieldName || ''
        const toFormType = item.field?.formType || ''
        
        return (
          toEnName == ConnectorFieldEnNameEnum.Customer
          || toFormType == ConnectorFieldTypeEnum.Customer
        )
        
      })
      
      if (isFalsy(customerField)) {
        
        message.error(t('common.connector.validate_rule.add'))
        
        return false
      }
      
      // 客户字段是否有值
      const isHaveCustomerFieldValue = (
        customerField!.rightFieldValue
        || (
          isNotEmpty(customerField!.value) && customerField!.value?.every(Boolean)
        )
      )
      
      if (isFalsy(isHaveCustomerFieldValue)) {
        
        message.error(t('common.connector.validate_rule.set'))
        
        return false
      }
      
    }
    
    
  }
  
  return true
}

export {
  connectorSaveValidate
}
